package plugins.flavours;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class HTTPpost {

	public HTTPpost() {
		
	}
	
	/**
	 * HTTP POST request to a specified URL.
	 * 
	 * @param target
	 * 			target URL
	 * @param keysAndValues
	 * 			"key1", "value1", "key2", "value2" ...
	 * @throws Exception
	 */
	public String prepareAndPost(String target, String... keysAndValues) throws Exception {
		int len = keysAndValues.length;
		String post = "";
		for (int i = 0; i < len; i++) {
			post += URLEncoder.encode(keysAndValues[i], "UTF-8");
			if (i%2 == 0) post += "=";
			else if (i<len-1) post += "&";
		}
		return post(target, post);
	}
	
	private String post(String target, String post) throws Exception {
		String response = "";
		URL url = new URL(target);
		URLConnection conn = url.openConnection();
		// connection parameters
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		// Make server believe we are form data...
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		// Write bytes to output stream
		out.writeBytes(post);
		out.flush ();
		out.close ();
		// Read response from the input stream.
		BufferedReader in = new BufferedReader (new InputStreamReader(conn.getInputStream ()));
		String temp;
		while ((temp = in.readLine()) != null){
			response += temp + "\n";
		}
		temp = null;
		in.close();
		System.out.println("Server response:\n'" + response + "'");
		return response;
	}
}
